module t_key_debounce(
    input sys_clk,
    input sys_rst_n,
    input key,
    output reg key_filter
);

parameter CNT_MAX = 20'd1_000_000;
reg [19:0] cnt;
reg key_dly;
reg key_dly2;

always @(posedge sys_clk or negedge sys_rst_n) begin
    if(!sys_rst_n)begin
        key_dly <= 1'b1;
        key_dly2<= 1'b1;
    end
    else begin
        key_dly <= key;
        key_dly2<= key_dly;
    end
end

always @(posedge sys_clk or negedge sys_rst_n) begin
    if(!sys_rst_n)
        cnt <= 20'b0;
    else if (key_dly2 != key)
        cnt <= 1'b0;
    else if(cnt < CNT_MAX)
        cnt <= cnt + 20'd1;
    else
        cnt <= cnt;
end

always @(posedge sys_clk or negedge sys_rst_n) begin
    if(!sys_rst_n)
        key_filter <= 1'b1;
    else if (key_dly2 != key)
        key_filter <= 1'b1;
    else if(cnt == CNT_MAX && ~key)
        key_filter <= 1'b0;
    else
        key_filter <= 1'b1;
end

endmodule